<template>
    <div style="height: 85%;position: relative">
      <el-scrollbar height="700px" style="padding: 20px">
        <div style="width: 100%;">
            <el-input placeholder="航点任务名" style="color: black;width: 90%" v-model="store.state.currentFlightTask.flightTaskName"
                      clearable maxlength="30" autofocus
            :disabled="nameInput"></el-input>
<!--          <el-input placeholder="航点任务名" style="color: black;width: 90%" v-model="store.state.currentFlightTask.flightTaskName"-->
<!--          clearable maxlength="30" aria-required="true"></el-input>-->

          <hr>
          <div style="font-size: small;padding-left: 20px;text-align: left">
            <p>航线长度:&nbsp;{{3468.26}}m</p>
            <p>预计执行航线时间:&nbsp;{{30}}min</p>
            <p>航点数:&nbsp;{{16}}</p>
            <p>预计拍照数:&nbsp;{{13}}</p>
          </div>
          <hr>
<!--          无人机模型选择-->
          <el-select v-model="aircraftID" placeholder="无人机模型选择" style="color: black; width:90%">
            <el-option
                v-for="item in getAircraft"
                :key="item.id"
                :label="item.type"
                :value="item.id"
                :disabled="item.isAvailable"
            >
            </el-option>
          </el-select >
<!--          航线高度设置-->
          <hr>
          <div >
            <span style="font-size: small;padding-left: 20px" >航线高度（m）</span>
            <el-slider  v-model="defaultHeight"
                        :max=50
                        :min=1
                        input-size="mini"
                        show-input
                        @change="changeDefaultHeight"
                        :disabled="heightSlider"
                        style="margin: 10px; width:90%;color: white">
            </el-slider>
          </div>
          <hr>

<!--          航线速度设置-->
          <div >
            <span style="font-size: small;padding-left: 20px" >航线速度（m/s）</span>
            <el-slider  v-model="defaultVelocity"
                        :min="0.2"
                        :max="13"
                        input-size="mini"
                        show-input
                        step="0.1"
                        @change = "changeDefaultVelocity"
                        :disabled="velocitySlider"
                        style="margin: 10px; width:90%;color: white">
            </el-slider>
          </div>
          <hr>
          <el-button type="primary" plain style="width: 90%;display: inline-block;"
                     @click.once="finishPathEdit"
                     :disabled="finishEditButton"
          >航点编辑确认</el-button>
          <hr>
        </div>
      </el-scrollbar>
    </div>
    <div style="position:relative;height: 5%;text-align: center;padding: 10px">
      <el-button round type="primary" v-if="this.store.state.createTaskButtonSwitch"
                 style="width: 90%;display: inline-block;" @click="saveFlightTask"
                 :disabled="saveButton"
      >保存任务</el-button>
      <el-button round type="primary" v-if="this.store.state.updateTaskButtonSwitch"
                 style="width: 90%;display: inline-block;" @click="updateFlightTask"
                 :disabled="updateButton"
      >更新任务</el-button>
    </div>
    <div style="position:relative;height: 5%;text-align: center;" >
      <el-button round type="primary" style="width: 40%" @click="back">返回</el-button>
      <el-button round type="primary" style="width: 40%" @click="startTask">开始飞行</el-button>
    </div>

</template>

<script>
import request from "@/utils/request";
import moment from 'moment'
import { ElMessageBox ,ElMessage,ElLoading,ElNotification} from 'element-plus'
export default {
  name: "RightAside",
  components:{},
  mounted() {
    let user = JSON.parse(sessionStorage.getItem("user"));
    console.log(user.permission)
    if(user.permission===2){
      console.log("没有权限")
      this.finishPathEdit();
      this.finishEditButton = true;
      this.saveButton = true;
      this.updateButton = true;
      this.velocitySlider = true;
      this.heightSlider = true;
      this.nameInput = true;
    }
    if(this.store.state.isUpdateRL===true){
      this.store.state.map.setCenter(this.store.state.currentPath[0]);
    }
    if(this.store.state.currentFlightTask.defaultHeight!==undefined) {
      this.defaultVelocity = this.store.state.currentFlightTask.defaultVelocity;
      this.defaultHeight = this.store.state.currentFlightTask.defaultHeight;
    }
  },
  data(){
    return{
      timeout:0,
      store:this.$store,
      defaultHeight:5,
      defaultVelocity:1,
      aircraftID:"",
      uvaMark:{},
      finishEditButton:false,
      updateButton:false,
      saveButton:false,
      velocitySlider:false,
      heightSlider:false,
      nameInput:false,
      firstMove:1,
      passedPath:[]
    }

  },
  unmounted() {
    window.clearTimeout(this.timeout)
  },
  methods:{
    updateAircraftInfo:function (){
      request.get("/aircraftman/updateaircraftinfo/"+this.store.state.currentUVAId).then(res=>{
        if(res) {
          let aircraftInfo = res.data;
          if(Object.getOwnPropertyNames(aircraftInfo).length!==0){//非空{}
            if(this.firstMove===1){
              this.uvaMark.setPosition([aircraftInfo.location.longitude,aircraftInfo.location.latitude]);
              this.firstMove=0;
            }else{
              this.uvaMark.moveTo([aircraftInfo.location.longitude,aircraftInfo.location.latitude], {
                duration:1000,
                autoRotation:false
              });
            }

            //更新无人机信息
            this.store.commit('updateCurrentUVAInfo',aircraftInfo);
          }
        }
        this.timeout=setTimeout(() => {
          this.updateAircraftInfo();
        }, 1000);
      });
    },
    finishPathEdit:function (){
      this.store.commit('closePolyEditor');
      //if(this.store.state.isUpdateRL===false){
        this.store.commit('initializeCurrentHeight',this.defaultHeight);
        this.store.commit('initializeCurrentVelocity',this.defaultVelocity);
      //}
    },
    updateFlightTask:function (){
      if(this.store.state.currentFlightTask.flightTaskName==null){
        ElNotification({
          title:'警告',
          message:'请检查任务名输入是否正确！',
          type:'error',
          position: 'top-right',
        });
      }else if(this.store.state.currentPath.length===0){
        ElNotification({
          title:'警告',
          message:'请检查任务路径设置是否正确！',
          type:'error',
          position: 'top-right',
        });
      } else {
        request.post("/flight_task/update",{
          flightTaskID:this.store.state.currentFlightTask.flightTaskId,
          flightTaskName:this.store.state.currentFlightTask.flightTaskName,
          flightTaskDefaultVelocity:this.store.state.currentFlightTask.defaultVelocity,
          flightTaskDefaultHeight:this.store.state.currentFlightTask.defaultHeight,
          flightTaskPath:this.store.state.currentPath,
          flightTaskHeight:this.store.state.currentHeight,
          flightTaskVelocity:this.store.state.currentVelocity,
          createTime:moment(this.store.state.currentFlightTask.createTime).format("YYYY-MM-DD"),
          updateTime:moment(new Date()).format("YYYY-MM-DD")
        }).then(res => {
          // alert(res.data.code+" "+res.data.msg);
          ElMessageBox.alert(res.data.msg, "Code:" + res.data.code);
        }).catch(error => {
          console.log(error);
        });
      }
    },
    saveFlightTask: function () {
      if(this.store.state.currentFlightTask.flightTaskName==null){
        ElNotification({
          title:'警告',
          message:'请检查任务名输入是否正确！',
          type:'error',
          position: 'top-right',
        });
      }else if(this.store.state.currentPath.length===0){
        ElNotification({
          title:'警告',
          message:'请检查任务路径设置是否正确！',
          type:'error',
          position: 'top-right',
        });
      } else {
        request.post("/flight_task/create", {
          flightTaskName: this.store.state.currentFlightTask.flightTaskName,
          flightTaskDefaultVelocity: this.store.state.currentFlightTask.defaultVelocity,
          flightTaskDefaultHeight: this.store.state.currentFlightTask.defaultHeight,
          flightTaskPath: this.store.state.currentPath,
          flightTaskHeight: this.store.state.currentHeight,
          flightTaskVelocity: this.store.state.currentVelocity,
          createTime: moment(new Date()).format("YYYY-MM-DD"),
          updateTime: moment(new Date()).format("YYYY-MM-DD")
        }).then(res => {
          // alert(res.data.code+" "+res.data.msg);
          ElMessageBox.alert(res.data.msg, "Code:" + res.data.code);
        }).catch(error => {
          console.log(error);
        });
      }
    },
    back:function (){
      this.store.commit('taskListViewOnAndOff',true);
      this.store.commit('rightAsideOnAndOff',false);
      let map = this.store.state.map;
      this.store.commit('closePolyEditor');
      map.clearMap();
      //刷新所有无人机任务
      request.get("/flight_task/list").
      then(res=>{
        if(res){
          //console.log(res.data);
          this.store.commit('updateFlightTasks',res.data);
        }else {
          console.log("请求飞行任务资源失败")
        }
      })
    },
    startTask:function (){
      ElMessageBox.confirm(
          '是否令编号为：'+this.aircraftID+'的无人机执行任务：'+this.store.state.currentFlightTask.flightTaskName+'?',
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
            request.post("/aircraftman/assigntask",{
              aircraftID:this.aircraftID,
              flightTaskName:this.store.state.currentFlightTask.flightTaskName,
              flightTaskDefaultVelocity:this.store.state.currentFlightTask.defaultVelocity,
              flightTaskDefaultHeight:this.store.state.currentFlightTask.defaultHeight,
              flightTaskPath:this.store.state.currentPath,
              flightTaskHeight:this.store.state.currentHeight,
              flightTaskVelocity:this.store.state.currentVelocity,
              createTime:moment(new Date()).format("YYYY-MM-DD"),
              updateTime:moment(new Date()).format("YYYY-MM-DD")
            }).then(res=>{
              let loadingInstance = ElLoading.service({
                fullscreen:true,
                background:"rgba(0, 0, 0, 0.8)",
                text:"正在为无人机分配任务......",
              });
              setTimeout(()=>{},5000);
              loadingInstance.close();
              // ElMessage({
              //   type: 'info',
              //   message: res.data.code+":"+res.data.msg,
              // });
              let aircrafts = this.store.state.aircraft;
              let currentId = this.aircraftID;
              let aircraft = aircrafts[0];
              for(let i=0;i<aircrafts.length;i++){
                if(aircrafts[i].id===currentId){
                  aircraft = aircrafts[i];
                  break;
                }
              }


              if(aircraft.flyCause===1){
                if(res.data.code===0){
                  //打开控制界面
                  this.store.commit('rightAsideEditorOnAndOff',false);
                  this.store.commit('rightAsideControllerOnAndOff',true);
                  //保存当前正在执行任务的无人机Id
                  this.store.commit('setCurrentUVAId',this.aircraftID);
                  //打开日志
                  this.store.commit('setLogVisible',true);
                  this.store.commit('addLogInfo','无人机开始执行任务');
                  //展示无人机位置图标
                  let myAMap = this.store.state.AMap;
                  let myMap = this.store.state.map;
                  this.uvaMark = new myAMap.Marker({
                    //position: new myAMap.LngLat(116.360734, 30.541093),
                    icon: require('../assets/aircraft.png'),//vue中对图片的映入需要require
                  });

                  this.uvaMark.on('moving',function (e){
                    //this.passedPath.push(e.passedPath);
                    let passedPolyline = new myAMap.Polyline({
                      map:myMap,
                      strokeColor:"#A14",
                      strokeWeight:6,
                      showDir:true
                    });
                    passedPolyline.setPath(e.passedPath);
                    //myMap.setCenter(e.target.getPosition(),true)
                  });
                  myMap.add(this.uvaMark);
                  //myMap.add(passedPolyline);
                  //开始更新当前无人机信息
                  this.updateAircraftInfo();
                }
              }else if(aircraft.flyCause===2){
                ElMessageBox.alert("无人机电量不足！");
              }else if(aircraft.flyCause===3){
                ElMessageBox.alert("GPS信号弱！");
              }else {
                ElMessageBox.alert("预期外的错误！");
              }
            });
          }).catch(() => {
            ElMessage({
              type: 'info',
              message: '任务取消',
            });
          })
      },
    changeDefaultHeight:function (){
      this.store.commit('setCurrentFlightTaskDefaultHeight',this.defaultHeight);
      this.store.commit('initializeCurrentHeight');
    },
    changeDefaultVelocity:function (){
      this.store.commit('setCurrentFlightTaskDefaultVelocity',this.defaultVelocity);
      this.store.commit('initializeCurrentVelocity');
    },

  },
  computed:{
    getAircraft:function (){

      return this.store.getters.getAircraft;
    }
  }
}
</script>

<style scoped>

</style>